﻿/*
 * Created by SharpDevelop.
 * User: Christian Pacella
 * Date: 2010/10/29
 * Time: 11:14 PM
 */
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.Serialization;

using ICSharpCode.TextEditor.Document;
using Microsoft.CSharp;

namespace Crianthis.MiniCompiler
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
    {
		// Define the main application path.
        private static string pathApplication = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
												+ @"\" + Application.CompanyName 
                                                + @"\" + Application.ProductName + @"\";
		
        // Define the snippets path.
        private static string pathSnippets = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
												+ @"\" + Application.CompanyName 
												+ @"\" + Application.ProductName + @"\Snippets";

        // Define the applications path.
        private static string pathExecutables = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
												+ @"\" + Application.CompanyName 
												+ @"\" + Application.ProductName + @"\Applications";
        
        // Define the compiler output executable file path.
        private static string filePath = string.Empty;

        // Define the user name.
        private static string userName = Environment.UserName;

        public MainForm()
        {
            InitializeComponent();
            
            // Initialise title bar and about menu from Assembly Info
            this.Text = String.Format(AssemblyTitle);
            this.aboutToolStripMenuItem.Text = String.Format("&About {0}...", AssemblyTitle);

            BuildFolderPath();
            ResetListView();
            ResetTextEditor();
        }

        #region Assembly Attribute Accessors

        public string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        public string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        public string AssemblyDescription
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyDescriptionAttribute)attributes[0]).Description;
            }
        }

        public string AssemblyProduct
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        public string AssemblyCopyright
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            }
        }

        public string AssemblyCompany
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }

        #endregion

        #region FileAndFolderFunctions
        
        private void BuildFolderPath()
        {
        	// Create the default folder structure:
        	// My Documents -> Application.ProductName
            if (!Directory.Exists(pathApplication))
            {
                Directory.CreateDirectory(pathApplication);
                Directory.CreateDirectory(pathSnippets);
                Directory.CreateDirectory(pathExecutables);
            }
        }

        private bool LoadCode()
        {
            //Create a OpenFileDialog instance to use
            OpenFileDialog openDialog = new OpenFileDialog();

            //We select what types are permitted to open
            openDialog.Filter = "C# Source Files (*.cs)|*.cs|All files (*.*)|*.*";

            //A title for the dialogbox
            openDialog.Title = "Open C# Source File";

            openDialog.InitialDirectory = pathSnippets;

            //If the user press cancel then end this void
            if (openDialog.ShowDialog() == DialogResult.Cancel)
            {
                return false;
            }

            //Create a filestream
            FileStream fStr;

            try
            {
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Opening " + openDialog.FileName + "...";
                
                //Set filestream to the result of the pick of the user
                fStr = new FileStream(openDialog.FileName, FileMode.Open, FileAccess.Read);

                //Create a streamreader, sr, to read the file
                StreamReader sr = new StreamReader(fStr);

                sourceTextEditor.Text = string.Empty;

                // hourglass cursor
                Cursor.Current = Cursors.WaitCursor;
                
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Opening " + openDialog.FileName + "...";
                
	            //While the end of the file has not been reached...
                while (sr.Peek() >= 0)
                {
                    //Create a 'line' that contains the current line of the textfile
                    string line = sr.ReadLine();

                    //Enter the text into the main textbox together with a new line
                    sourceTextEditor.Text += line + Environment.NewLine;
                }

                //Close the file so other modules can access it
                sr.Close();
                
                // Set the file name.
                filePath = openDialog.FileName;

                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Opened " + openDialog.FileName;

                // Update the tab label
                tabPageSource.Text = Path.GetFileName(openDialog.FileName);
                
                return true;
                
            }
            catch (Exception ex)
            {
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Error Opening " + openDialog.FileName;

                // Notify the user.
                MessageBox.Show("Error opening the file:" + Environment.NewLine + ex.ToString(), 
                                Application.ProductName, 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
                
                
                return false;
            }
            finally
            {
                // Dispose of the open dialog.
	            openDialog.Dispose();
	            openDialog = null;

	            // Default cursor
                Cursor.Current = Cursors.Default;
            }
        }

        private bool SaveCode()
        {
        	try
        	{
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Saving " + filePath + "...";

                // Save the file.
                sourceTextEditor.SaveFile(filePath);
                
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Saved " + filePath;
                
                // Update the tab label
                tabPageSource.Text = Path.GetFileName(filePath);

                // Default cursor
                Cursor.Current = Cursors.Default;
				
        		return true;
        	}
            catch (Exception ex)
            {
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Error Saving " + filePath;

                // Notify the user.
                MessageBox.Show("Error saving the file:" + Environment.NewLine + ex.ToString(), 
                                Application.ProductName, 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);

	            // Default cursor
                Cursor.Current = Cursors.Default;
                
                return false;
            }
        }

        private bool SaveCodeAs()
        {
            // Create new SaveFileDialog object
            SaveFileDialog DialogSave = new SaveFileDialog();

            // Default file extension
            DialogSave.DefaultExt = "cs";

            // Available file extensions
            DialogSave.Filter = "C# Source Files (*.cs)|*.cs|All files (*.*)|*.*";

            // Adds a extension if the user does not
            DialogSave.AddExtension = true;

            // Restores the selected directory, next time
            DialogSave.RestoreDirectory = true;

            // Dialog title
            DialogSave.Title = "Save C# Source File";

            // Startup directory
            DialogSave.InitialDirectory = pathSnippets;
            DialogSave.FileName = tabPageSource.Text;

            // Show the dialog and process the result
            if (DialogSave.ShowDialog() == DialogResult.OK)
            {
            	try
            	{
	                // Update status bar
	                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Saving " + DialogSave.FileName + "...";
	
	                // Save the fle.
	                sourceTextEditor.SaveFile(DialogSave.FileName);
	                filePath = DialogSave.FileName;
	                
	                // Update status bar
	                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Saved " + DialogSave.FileName;
	                
	                // Update the tab label
	                tabPageSource.Text = Path.GetFileName(DialogSave.FileName);
	
	                // Default cursor
	                Cursor.Current = Cursors.Default;
	                
	                // Dispose of the save dialog.
					DialogSave.Dispose();
					DialogSave = null;
					
            		return true;
            	}
	            catch (Exception ex)
	            {
	                // Update status bar.
	                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Error Saving " + DialogSave.FileName;
	
	                // Notify the user.
	                MessageBox.Show("Error saving the file:" + Environment.NewLine + ex.ToString(), 
	                                Application.ProductName, 
	                                MessageBoxButtons.OK, 
	                                MessageBoxIcon.Error);
	                
	                // Dispose of the save dialog.
		            DialogSave.Dispose();
		            DialogSave = null;
	
		            // Default cursor
	                Cursor.Current = Cursors.Default;
	                
	                return false;
	            }
            }
       		return false;
        }

        #endregion

        #region DateAndTimeFunctions

        private String GetLongTimestamp()
        {
        	// Return a formatted date/time string.
            return DateTime.Now.ToString("yyyyMMddHHmmssffff");
        }

        private String GetShortTimestamp()
        {
        	// Return a formatted date/time string.
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff");
        }

        #endregion
        
        #region FormControlResetFunctions
        
        private void ResetTextEditor()
        {
        	// Simulate creating a new winforms code template.
        	winFormToolStripMenuItemClick(null, null);
        }

        private void ClearTextEditor()
        {
        	// Clear the code editor.
            sourceTextEditor.Text = string.Empty;
        }

        private void ResetListView()
        {
            // Prepare the list view
            errorsListView.Clear();
            ColumnHeader colHead;

            colHead = new ColumnHeader();
            colHead.Text = "Line #";
            colHead.Width = 50;
            this.errorsListView.Columns.Add(colHead);

            colHead = new ColumnHeader();
            colHead.Text = "Col #";
            colHead.Width = 50;
            this.errorsListView.Columns.Add(colHead);

            colHead = new ColumnHeader();
            colHead.Text = "Error #";
            colHead.Width = 50;
            this.errorsListView.Columns.Add(colHead);

            colHead = new ColumnHeader();
            colHead.Text = "Error Message";
            colHead.Width = 300;
            this.errorsListView.Columns.Add(colHead);
        }

        #endregion
        
        #region BuildFunctions
        
        private bool BuildAndRunCode()
        {
			try
			{
	        	// Show the hourglass cursor.
	            Cursor.Current = Cursors.WaitCursor;
	            
	            // Clear any errors.
	            ResetListView();
	            
	            MiniApp myApp = new MiniApp();
	            
				// Construct an instance of the XmlSerializer with the type
				// of object that is being deserialized.
				XmlSerializer mySerializer = 
				new XmlSerializer(typeof(MiniApp));
				
				// To read the file, create a FileStream.
				FileStream myFileStream = 
				new FileStream("myApp.xml", FileMode.Open);
				
				// Call the Deserialize method and cast to the object type.
				myApp = (MiniApp) 
				mySerializer.Deserialize(myFileStream);
				
				myFileStream.Close();
				
	            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
	
	            // Update status bar
	            toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Start...";
	
	            System.CodeDom.Compiler.CompilerParameters compilerParams = new CompilerParameters();
	
	            //Make sure we generate an EXE, not a DLL
	            compilerParams.GenerateExecutable = true;
	            compilerParams.ReferencedAssemblies.Add("System.dll");
	            compilerParams.ReferencedAssemblies.Add("System.Drawing.dll");
	            compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
	            
	            // Add compiler options
	            string compilerOptions = string.Empty;
	            
	            if (myApp.WinFormsExecutable)
	            {
	            	compilerOptions = "/target:winexe /optimize";
		            if (myApp.IncludeAssemblyIcon)
		            {
		            	compilerOptions += string.Format(" /win32icon:\"{0}\"", myApp.AssemblyIconFileName);
		            }
	            }
	            else
	            {
	            	compilerOptions = "/optimize";
	            }
	            
	            compilerParams.CompilerOptions = compilerOptions;
	            
	            // Set the output assembly
	            compilerParams.OutputAssembly = myApp.ApplicationFilePath + @"\\" + myApp.ApplicationFileName;
	
	            CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, sourceTextEditor.Text);
	
	            if (results.Errors.Count > 0)
	            {
	                ResetListView();
	                ListViewItem lvi;
	                ListViewItem.ListViewSubItem lvsi;
	                this.errorsListView.BeginUpdate(); 
	                
	                foreach (CompilerError CompErr in results.Errors)
	                {
	                    lvi = new ListViewItem();
	                    lvi.Text = CompErr.Line.ToString();
	                    lvi.ImageIndex = 0;
	                    lvi.Tag = CompErr.ErrorNumber;
	
	                    lvsi = new ListViewItem.ListViewSubItem();
	                    lvsi.Text = CompErr.Column.ToString();
	                    lvi.SubItems.Add(lvsi);
	
	                    lvsi = new ListViewItem.ListViewSubItem();
	                    lvsi.Text = CompErr.ErrorNumber.ToString();
	                    lvi.SubItems.Add(lvsi);
	
	                    lvsi = new ListViewItem.ListViewSubItem();
	                    lvsi.Text = CompErr.ErrorText;
	                    lvi.SubItems.Add(lvsi);
	                    
	                    if (CompErr.IsWarning)
	                    {
		                    lvi.ImageIndex = 0;
	                    }
	                    else
	                    {
	                    	lvi.ImageIndex = 1;
	                    }
	                    
	                    this.errorsListView.Items.Add(lvi);
	                }

	                // Update status bar
	                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Failed!";
	
	                this.errorsListView.EndUpdate();
	                this.errorsListView.View = View.Details;
	            }
	            else
	            {
	                // Update status bar
	                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Success!";

	                // Run the application
	                System.Diagnostics.Process.Start(myApp.ApplicationFilePath + @"\\" + myApp.ApplicationFileName);
	            }
	            // Default cursor
	            Cursor.Current = Cursors.Default;
	            return true;
			}
			catch (Exception ex)
			{
                // Update status bar
                toolStripStatusLabel.Text = @"[" + GetShortTimestamp() + "] Failed!";
	            // Default cursor
	            Cursor.Current = Cursors.Default;
                MessageBox.Show("Error Building File:" + Environment.NewLine + ex.ToString(), Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;				
			}
        }

        #endregion

        #region WindowsFormsControlEventHandlers
        
        private void MainFormLoad(object sender, EventArgs e)
		{
			// Prepare the code highlighter text box
            sourceTextEditor.Document.HighlightingStrategy = 
                HighlightingManager.Manager.FindHighlighter("C#");			
		}

		private void openToolStripButton_Click(object sender, EventArgs e)
        {
			// Load code into the code editor.
            LoadCode();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        	// Show the About form.
            AboutForm formAbout = new AboutForm();
            formAbout.ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
        	// Close the main form.
        	this.Close();
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
			// Save the file.
			if (!string.IsNullOrEmpty(sourceTextEditor.Text))
		    {
        		// Just save the file.
	        	SaveCode();
		    }
            else
            {
            	// Notify the user
                MessageBox.Show("There is no code to save.", 
            	                Application.ProductName, 
            	                MessageBoxButtons.OK, 
            	                MessageBoxIcon.Error);
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
			// Save the file.
			if (!string.IsNullOrEmpty(sourceTextEditor.Text))
		    {
        		// Just save the file.
	        	SaveCode();
		    }
            else
            {
            	// Notify the user
                MessageBox.Show("There is no code to save.", 
            	                Application.ProductName, 
            	                MessageBoxButtons.OK, 
            	                MessageBoxIcon.Error);
            }
        }

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
        	// Reset the code editor.
            ResetTextEditor();
        }

        private void copyToolStripButton_Click(object sender, EventArgs e)
        {
        	// Copy the code to the clipboard.
        	if (!string.IsNullOrEmpty(sourceTextEditor.Text))
            {
                Clipboard.SetText(sourceTextEditor.Text);
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
        	// Load code into the editor.
            LoadCode();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
        	// Reset the code in the code editor.
            ResetTextEditor();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        	// Paste from the clipboard.
        	if (Clipboard.ContainsText())
            {
                sourceTextEditor.Text = Clipboard.GetText();
            }
        }

        private void pasteToolStripButton_Click(object sender, EventArgs e)
        {
        	// Paste from the clipboard.
            if (Clipboard.ContainsText())
            {
                sourceTextEditor.Text = Clipboard.GetText();
            }
        }
		
		private void buildrunToolStripMenuItem_Click(object sender, EventArgs e)
		{
            MiniApp myApp = new MiniApp();
            
			// Construct an instance of the XmlSerializer with the type
			// of object that is being deserialized.
			XmlSerializer mySerializer = 
			new XmlSerializer(typeof(MiniApp));
			
			// To read the file, create a FileStream.
			FileStream myFileStream = 
			new FileStream("myApp.xml", FileMode.Open);
			
			// Call the Deserialize method and cast to the object type.
			myApp = (MiniApp) 
			mySerializer.Deserialize(myFileStream);
			
			myFileStream.Close();
			
			// Check if there is code to build.
			if (!string.IsNullOrEmpty(sourceTextEditor.Text))
            {
				if (myApp.SaveBeforeBuild)
				{
		        	if (tabPageSource.Text == "Untitled.cs")
		        	{
		        		// First time save.
						SaveCodeAs();
		        	}
		        	else
		        	{
		        		// Just save the file.
			        	SaveCode();
		        	}
				}
	        	
        		// Build the code.
                BuildAndRunCode();
            }
            else
            {
            	// Notify the user
                MessageBox.Show("There is no code to build and run.", 
            	                Application.ProductName, 
            	                MessageBoxButtons.OK, 
            	                MessageBoxIcon.Error);
            }
		}
		
		private void settingsToolStripMenuItemClick(object sender, EventArgs e)
		{
			// Show the configuration dialog box.
			ConfigForm configForm = new ConfigForm();
			configForm.ShowDialog();
		}
		
		private void consoleToolStripMenuItemClick(object sender, EventArgs e)
		{
			// Insert default code into the code editor.
            sourceTextEditor.Text = @"#region Read me please" + Environment.NewLine + Environment.NewLine 
                                      + "	// Application Name: MyApp" + Environment.NewLine 
                                      + "	// Created by " + Application.ProductName + Environment.NewLine 
            						  + "	// Date Created: " + GetShortTimestamp() + Environment.NewLine
                                      + "	// Author: " + userName + Environment.NewLine + Environment.NewLine 
                                      + "#endregion" + Environment.NewLine + Environment.NewLine 
                                      + "#region Using directives" + Environment.NewLine + Environment.NewLine 
                                      + "	using System;" + Environment.NewLine 
                                      + "	using System.Reflection;" + Environment.NewLine 
                                      + "#endregion" + Environment.NewLine + Environment.NewLine 
                                      + "#region Assembly attributes" + Environment.NewLine + Environment.NewLine 
                                      + "	[assembly: AssemblyTitle(\"MyApp\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyProduct(\"MyApp\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyVersion(\"1.0.*\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyDescription(\"Created by " + Application.ProductName + "\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyCompany(\"" + Application.ProductName + "\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyCopyright(\"Copyright © " + DateTime.Now.Year + "\")]" + Environment.NewLine + Environment.NewLine 
                                      + "#endregion" + Environment.NewLine + Environment.NewLine 
                                      + "namespace MyApp" + Environment.NewLine 
                                      + "{" + Environment.NewLine
                                      + "	/// <summary>" + Environment.NewLine
                                      + "	/// Summary description for MyAppClass." + Environment.NewLine
                                      + "	/// </summary>" + Environment.NewLine
                                      + "	class MyAppClass" + Environment.NewLine
                                      + "	{" + Environment.NewLine
                                      + "		static void Main(string[] args)" + Environment.NewLine
                                      + "		{" + Environment.NewLine
                                      + "			Console.WriteLine(\"Welcome to MyApp!\");" + Environment.NewLine
                                      + "			Console.ReadLine();" + Environment.NewLine
                                      + "		}" + Environment.NewLine
                                      + "	}" + Environment.NewLine
                                      + "}";	
            // Set the filename.
            tabPageSource.Text = "Untitled.cs";
            filePath = string.Empty;
		}
		
		private void winFormToolStripMenuItemClick(object sender, EventArgs e)
		{
			// Insert default code into the code editor.
            sourceTextEditor.Text = @"#region Read me please" + Environment.NewLine + Environment.NewLine 
                                      + "	// Application Name: MyApp" + Environment.NewLine 
                                      + "	// Created by " + Application.ProductName + Environment.NewLine 
            						  + "	// Date Created: " + GetShortTimestamp() + Environment.NewLine
                                      + "	// Author: " + userName + Environment.NewLine + Environment.NewLine 
                                      + "#endregion" + Environment.NewLine + Environment.NewLine 
                                      + "#region Using directives" + Environment.NewLine + Environment.NewLine 
                                      + "	using System;" + Environment.NewLine 
                                      + "	using System.Drawing;" + Environment.NewLine 
                                      + "	using System.Reflection;" + Environment.NewLine 
                                      + "	using System.Windows.Forms;" + Environment.NewLine + Environment.NewLine 
                                      + "#endregion" + Environment.NewLine + Environment.NewLine 
                                      + "#region Assembly attributes" + Environment.NewLine + Environment.NewLine 
                                      + "	[assembly: AssemblyTitle(\"MyApp\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyProduct(\"MyApp\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyVersion(\"1.0.*\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyDescription(\"Created by " + Application.ProductName + "\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyCompany(\"" + Application.ProductName + "\")]" + Environment.NewLine 
                                      + "	[assembly: AssemblyCopyright(\"Copyright © " + DateTime.Now.Year + "\")]" + Environment.NewLine + Environment.NewLine 
                                      + "#endregion" + Environment.NewLine + Environment.NewLine 
                                      + "namespace MyApp" + Environment.NewLine 
                                      + "{" + Environment.NewLine 
                                      + "	/// <summary>" + Environment.NewLine 
                                      + "	/// Summary description for MyForm class." + Environment.NewLine 
                                      + "	/// </summary>" + Environment.NewLine 
                                      + "	class MyForm : Form" + Environment.NewLine 
                                      + "	{" + Environment.NewLine 
                                      + "		Label Label1;" + Environment.NewLine + Environment.NewLine 
                                      + "		public MyForm()" + Environment.NewLine 
                                      + "		{" + Environment.NewLine 
                                      + "			// Define a label, and specify its text to display, position and size" + Environment.NewLine 
                                      + "			Label1 = new Label();" + Environment.NewLine 
                                      + "			Label1.Text = \"Welcome to MyApp!\";" + Environment.NewLine 
                                      + "			Label1.AutoSize = true;" + Environment.NewLine 
                                      + "			Label1.Location = new Point(30,30);" + Environment.NewLine + Environment.NewLine 
                                      + "			// Text to be Displayed in the Caption-Title Bar" + Environment.NewLine 
                                      + "			this.Text = \"MyApp\";" + Environment.NewLine 
                                      + "			this.StartPosition = FormStartPosition.CenterScreen;" + Environment.NewLine 
                                      + "			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;" + Environment.NewLine 
                                      + "			this.MaximizeBox = false;" + Environment.NewLine 
                                      + "			this.Name = \"MainForm\";" + Environment.NewLine + Environment.NewLine 
                                      + "			// Add the label to the array of controls of the form" + Environment.NewLine 
                                      + "			this.Controls.Add(Label1);" + Environment.NewLine 
                                      + "		}" + Environment.NewLine + Environment.NewLine 
                                      + "		public static void Main()" + Environment.NewLine 
                                      + "		{" + Environment.NewLine 
                                      + "			// Start by using Application.Run()" + Environment.NewLine 
                                      + "			Application.Run(new MyForm());" + Environment.NewLine 
                                      + "		}" + Environment.NewLine 
                                      + "	}" + Environment.NewLine 
                                      + "}";
            // Set the filename.
            tabPageSource.Text = "Untitled.cs";
            filePath = string.Empty;
		}
		
		private void buildToolStripButtonClick(object sender, EventArgs e)
		{
            MiniApp myApp = new MiniApp();
            
			// Construct an instance of the XmlSerializer with the type
			// of object that is being deserialized.
			XmlSerializer mySerializer = 
			new XmlSerializer(typeof(MiniApp));
			
			// To read the file, create a FileStream.
			FileStream myFileStream = 
			new FileStream("myApp.xml", FileMode.Open);
			
			// Call the Deserialize method and cast to the object type.
			myApp = (MiniApp) 
			mySerializer.Deserialize(myFileStream);
			
			myFileStream.Close();
			
			// Check if there is code to build.
			if (!string.IsNullOrEmpty(sourceTextEditor.Text))
            {
				if (myApp.SaveBeforeBuild)
				{
		        	if (tabPageSource.Text == "Untitled.cs")
		        	{
		        		// First time save.
						SaveCodeAs();
		        	}
		        	else
		        	{
		        		// Just save the file.
			        	SaveCode();
		        	}
				}
	        	
        		// Build the code.
                BuildAndRunCode();
            }
            else
            {
            	// Notify the user
                MessageBox.Show("There is no code to build and run.", 
            	                Application.ProductName, 
            	                MessageBoxButtons.OK, 
            	                MessageBoxIcon.Error);
            }
		}
		
		private void configToolStripButtonClick(object sender, EventArgs e)
		{
			// Show the configuration dialog box.
			ConfigForm configForm = new ConfigForm();
			configForm.ShowDialog();
		}
		
		private void saveToolStripButtonClick(object sender, EventArgs e)
		{
			// Save the file.
			if (!string.IsNullOrEmpty(sourceTextEditor.Text))
		    {
	        	if (tabPageSource.Text == "Untitled.cs")
	        	{
	        		// First time save.
					SaveCodeAs();
	        	}
	        	else
	        	{
	        		// Just save the file.
		        	SaveCode();
	        	}
		    }
            else
            {
            	// Notify the user
                MessageBox.Show("There is no code to save.", 
            	                Application.ProductName, 
            	                MessageBoxButtons.OK, 
            	                MessageBoxIcon.Error);
            }
		}
		
		private void saveAsToolStripMenuItemClick(object sender, EventArgs e)
		{
			// Save the file.
			if (!string.IsNullOrEmpty(sourceTextEditor.Text))
		    {
        		// Just save the file.
	        	SaveCode();
		    }
            else
            {
            	// Notify the user
                MessageBox.Show("There is no code to save.", 
            	                Application.ProductName, 
            	                MessageBoxButtons.OK, 
            	                MessageBoxIcon.Error);
            }
		}
		
		private void newToolStripButtonClick(object sender, EventArgs e)
		{
			// Reset the code editor.
			ResetTextEditor();
		}
		
		private void openToolStripButtonClick(object sender, EventArgs e)
		{
			// Load code into the code editor.
			LoadCode();
		}
		
		void printToolStripButtonClick(object sender, EventArgs e)
		{
			
		}
		
		void copyToolStripButtonClick(object sender, EventArgs e)
		{
        	// Copy the code to the clipboard.
        	if (!string.IsNullOrEmpty(sourceTextEditor.Text))
            {
                Clipboard.SetText(sourceTextEditor.Text);
            }
		}
		
		void cutToolStripButtonClick(object sender, EventArgs e)
		{
			
		}
		
		void pasteToolStripButtonClick(object sender, EventArgs e)
		{
        	// Paste from the clipboard.
            if (Clipboard.ContainsText())
            {
                sourceTextEditor.Text = Clipboard.GetText();
            }
		}
		
		#endregion
		
    }
}